package com.luoqian.demo01;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class UserTest {


    public static void main(String[] args) throws Exception {

        // 1.作用于属性上，field.setAccessible(true);
        Class<User> userClass = User.class;
        Constructor<User> constructor = userClass.getConstructor();
        User user = constructor.newInstance();
        Field[] declaredFields = userClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            declaredField.set(user,"mic");
        }
        System.out.println(user.toString());  // User{name='jack'}


        // 2.作用于方法上，method.setAccessible(true);
        Method myId = userClass.getDeclaredMethod("myId", null);
        myId.setAccessible(true);
        myId.invoke(user);

    }
}
